package com.sfilyh.servelt;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sfilyh.util.DBUtil;
import com.sfilyh.util.WebUtil;


@WebServlet("/password")
public class password extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		String password =  request.getParameter("password");
		
		String sql = "select password from tb_article where id = ?";
		boolean error = true;
		
		if(DBUtil.countResutSize("SELECT id  FROM tb_article_pass_logs WHERE TO_DAYS(trytime) = TO_DAYS(NOW()) AND article = ? AND ip = ?", id,WebUtil.getIp(request)) < 5){			
			Map<String, Object> rmap = DBUtil.queryForMap(sql, id);
			if(rmap != null && rmap.get("password") != null){
				String p = rmap.get("password").toString();
				if(p.equals(password)){
					Map<String,Boolean> map = (Map<String, Boolean>) request.getSession().getAttribute("artilce_pwd");
					if(map == null){
						map = new HashMap<String,Boolean>();
						map.put(id, true);
						request.getSession().setAttribute("artilce_pwd", map);
					}else{
						map.put(id, true);
					}
					error = false;
				}else{
					DBUtil.update("INSERT INTO tb_article_pass_logs(article,ip,trypass) VALUES(?,?,?)",id,WebUtil.getIp(request),password);
				}
			}			
		}else{
			DBUtil.update("INSERT INTO tb_article_pass_logs(article,ip,trypass) VALUES(?,?,?)",id,WebUtil.getIp(request),password);
		}
		
		String toUrl = request.getContextPath()+"/view?id="+id;
		if(error) toUrl = toUrl + "&error=true";
		
		response.sendRedirect(toUrl);		
	}

}
